package com.larry.rabbitmq.springbootrabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author larry
 * @Title: larry-rabbitmq
 * @Package com.larry.rabbitmq.springbootrabbitmq.config
 * @Description: TODO
 * @date 7/5/214:42 PM
 */

@Slf4j
@Component
public class MyCallback implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        //注入
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    /**
     * 交换机确认回调方法
     *      发消息 交换机接收到了 回调
     *          correlationData 保存回调消息的id及其相关信息
     *          交换机收到消息 true
     *          cause null
     *      发消息 交换机接收失败 回调
     * @param correlationData
     * @param ack
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData != null ? correlationData.getId() : "";
        if (ack){
            log.info("交换机收到消息,id为: {}",id);
        }else {
            log.info("交换机接收消息失败,id为: {},原因是: {}",id,cause);
        }
    }


    /**
     * 回退
     * @param message
     * @param replyCode
     * @param replyText
     * @param exchange
     * @param routingKey
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.error("消息 {} 被交换 {} 机退回,原因 {} 路由 {}",new String(message.getBody()),exchange,replyText,routingKey);
    }
}
